package risk.control.project.service;


import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import risk.control.project.framework.PostService;

/**
 * 记录登录失败次数，锁定用户
 */
@Service
public class AccountLockService extends PostService {

    @Qualifier("JedisPool")
    private final JedisPool jedisPool;

    public AccountLockService(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    public void setErrorCount(String userName) {
        //try块退出时，会自动调用res.close()方法，关闭资源。
        try (Jedis jedis = jedisPool.getResource()) {
            //记录该用户名对应错了几次密码
            String key = "log_failure_count_key_" + userName;
            long failuresCount = jedis.incr(key);//记录失败次数
            if (failuresCount == 1) {
                // 只有第一次递增时才设置过期时间
                jedis.expire(key, 60 * 5);
            }
        }
    }

    public int getErrorCount(String userName) {
        try (Jedis jedis = jedisPool.getResource()) {
            String key = "log_failure_count_key_" + userName;
            if (!jedis.exists(key)) {
                return 0;
            }
            String attempts = jedis.get(key);
            return attempts == null ? 0 : Integer.parseInt(attempts);
        }
    }

    public void clearLoginLock(String userName) {
        try (Jedis jedis = jedisPool.getResource()) {
            String key = "log_failure_count_key_" + userName;
            if (jedis.exists(key)) {
                //解除锁定
                jedis.del(key);
            }
        }
    }
}
